package com.atguigu.service.impl;

import com.atguigu.base.BaseDao;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.dao.AdminRoleDao;
import com.atguigu.dao.RoleDao;
import com.atguigu.entity.AdminRole;
import com.atguigu.entity.Role;
import com.atguigu.service.RoleService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@DubboService
@Transactional
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private AdminRoleDao adminRoleDao;
    // 为父类中抽取的公共方法提供一个具体的dao对象
    @Override
    protected BaseDao<Role> getEntityDao() {
        return roleDao;
    }
    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    public Map<String, Object> findRoleByAdminId(Long adminId) {
        //查询所有的Role的List集合
        List<Role>roles=roleDao.findAll();
        //准备两个集合
        //已经具备角色的list
        List<Role>assignRoleList= new ArrayList<>();
        //未具备角色的list
        List<Role>noAssignRoleList=new ArrayList<>();

        //查询当前用户所拥有的所有角色的id
        List<Long> roleIds =roleDao.findRoleIdsList(adminId);
        for (Role role : roles) {
            if (roleIds.contains(role.getId())) {
                assignRoleList.add(role);
            }else{
                noAssignRoleList.add(role);
            }
        }


        Map<String,Object>map=new HashMap<>();
        map.put("noAssginRoleList",noAssignRoleList );
        map.put("assginRoleList",assignRoleList);

        return map;
    }

    @Override
    public void saveUserRoleRealtionShip(Long adminId, Long[] roleIds) {
        //先删除当前用户的所有角色
        adminRoleDao.deleteByAdminId(adminId);
        if(null != roleIds && roleIds.length>0){
            for(Long roleId:roleIds){
                if(!StringUtils.isEmpty(roleId)){
                    AdminRole adminRole = new AdminRole();
                    adminRole.setAdminId(adminId);
                    adminRole.setRoleId(roleId);
                    adminRoleDao.insert(adminRole);

                }
            }
        }

    }


}
